package com.qf;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @author 孙亚梅
 * @version V1.0
 * @Project javase2203
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/6/8 19:47
 */
@Controller
@RequestMapping("/upload")
public class UploadController {


    /**
     * 跳转到上传页面
     * @return
     */
    @RequestMapping("/toUpload")
    public String toUpload() {
        return "fileupload";
    }

    /**
     * 文件上传
     * MultipartFile接口用来接收上传的文件, 但是变量名必须等于页面上传域的name属性
     * @return
     */
    @RequestMapping("/test1")
    @ResponseBody
    public String test1(MultipartFile source, HttpServletRequest request) throws Exception {
        //1. 获取完整的文件名
        String fileName = source.getOriginalFilename();
        //获取文件大小
        //long size = source.getSize();
        //获取文件内容
        //InputStream inputStream = source.getInputStream();
        //2. 获取文件保存路径
        String realPath = request.getServletContext().getRealPath("/upload");
        System.out.println("====realPath=======" + realPath);
        //3. 持久化保存到硬盘上
        source.transferTo(new File(realPath + "\\" + fileName));
        //4. 返回文件保存的路径字符串
        return "http://localhost:8080/upload/" + fileName;
    }



}
